package com.example.zhaohang.bingzhuangtu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.zhaohang.mvp.prsenter.LoginPresent;
import com.example.zhaohang.mvp.prsenter.LonginPresentImp;
import com.example.zhaohang.mvp.view.LoginView;
import com.example.zhaohang.utils.Sputiles;
import com.example.zhaohang.utils.ToastMake;
import com.example.zhaohang.zhuce.Register;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.ContactsPage;
import cn.smssdk.gui.RegisterPage;

import static com.example.zhaohang.bingzhuangtu.QQAppApolication.context;

public class LoginActivity extends BaseActivity implements TextView.OnEditorActionListener, LoginView, View.OnClickListener {


    private LoginPresent    mLoginPresent;
    private TextInputLayout mPawTextinputlayout;
    private TextInputLayout nameInputlayout;
    private EditText        longinName;
    private EditText        posworld;
    private Button        duanxinyanzheng;
    private TextView        otherLongin;
    private TextView        longinZhuce;
    private Button          duanxinyanzhengdenglu;
    private String          name;
    private String          psw;
    private boolean         mRegister;
    private boolean login=false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            StartActivity(MainActivity.class, true);
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        longinName = (EditText) findViewById(R.id.longin_name);
        duanxinyanzheng = (Button) findViewById(R.id.duanxinyanzheng);
        posworld = (EditText) findViewById(R.id.posworld);
        otherLongin = (TextView) findViewById(R.id.other_longin);
        longinZhuce = (TextView) findViewById(R.id.longin_zhuce);
        duanxinyanzhengdenglu = (Button) findViewById(R.id.duanxinyanzhengdenglu);
        otherLongin.setOnClickListener(this);
        longinZhuce.setOnClickListener(this);

        posworld.setOnEditorActionListener(this);

        mLoginPresent = new LonginPresentImp(this);
        mPawTextinputlayout = (TextInputLayout) findViewById(R.id.paw_textinputlayout);
        nameInputlayout = (TextInputLayout) findViewById(R.id.name_inputlayout);


        String name1 = Sputiles.getName();
        String psw1 = Sputiles.getPsd();


        //进行账号密码进行回现
        if (!TextUtils.isEmpty(name1)) {
            longinName.setText(name1);
        }
        if (!TextUtils.isEmpty(psw1)) {
            posworld.setText(Integer.parseInt(psw1)+"");
        }

        duanxinyanzhengdenglu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emsLogin();
            }
        });
        duanxinyanzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContactsPage contactsPage = new ContactsPage();
                contactsPage.show(QQAppApolication.context);
            }
        });

    }


    public void longingx(View view) {

        register();

        if (mRegister) {

            StartActivity(MainActivity.class, true);
            finish();
        }

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.other_longin:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                authorize(qq);

                break;
            case R.id.longin_zhuce:

                StartActivity(Register.class, false);
                break;
        }
    }


    //绑定键盘点击事件
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (v.getId() == R.id.posworld) {

            if (actionId == EditorInfo.IME_ACTION_DONE) {

                register();

                return true;
            }
        }


        return false;
    }

    public void register() {
        name = longinName.getText().toString().trim();
        psw = posworld.getText().toString().trim();

        Sputiles.saveName(name);
        Sputiles.savePsd(psw);
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(psw)) {

            showDialog("正在登录中.....");


        }

        if (!"text".equals(name)) {
            nameInputlayout.setEnabled(true);
            nameInputlayout.setError("用户名不合法");
            longinName.requestFocus(View.FOCUS_RIGHT);

            return;

        } else {
            nameInputlayout.setEnabled(false);
            nameInputlayout.setError("");

        }


        if (!"123".equals(psw)) {

            mPawTextinputlayout.setEnabled(true);

            mPawTextinputlayout.setError("密码错误");

            posworld.requestFocus(View.FOCUS_RIGHT);

            return;

        } else {

            mPawTextinputlayout.setEnabled(false);
            mPawTextinputlayout.setError("");
            //  showDialog("正在注册中.....");


            mRegister = mLoginPresent.register(name, psw);


        }



    }

    @Override
    public void hitDigle() {
        hidDialog();
    }

    //一键分享
    public void showShare(View view) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }

    //第三方登录
    private void authorize(Platform plat) {
//        if (plat == null) {
//            popupOthers();
//            return;
//        }
        //判断指定平台是否已经完成授权
        if(plat.isAuthValid()) {
            String userId = plat.getDb().getUserId();
//            if (userId != null) {
//                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
//                login(plat.getName(), userId, null);
//                return;
//            }
            //获取权限成功的话可以获得用户信息
            UpDataUserInfo(plat);
            //确认完就不需要其他的信息了;
            return;
        }

        plat.setPlatformActionListener(lisener);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(true);
        //获取用户资料
        plat.showUser(null);
    }



    private  PlatformActionListener lisener=new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

            //确认获取权限
            UpDataUserInfo(platform);

        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            //获取权限失败
            ToastMake.showToast("获取权限失败");

        }

        @Override
        public void onCancel(Platform platform, int i) {
            //取消授权
            ToastMake.showToast("您取消了授权");

        }
    };
    private void UpDataUserInfo(Platform plat) {
        //获取用户名字
        String userName = plat.getDb().getUserName();

        ToastMake.showToast(userName);

        //当名字不为空时
        if (!TextUtils.isEmpty(userName)){
            login = true;
            mHandler.sendEmptyMessage(0);
        }
    }
    public void emsLogin(){
        //打开注册页面
        RegisterPage registerPage = new RegisterPage();
        registerPage.setRegisterCallback(new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                // 解析注册结果
                //也就是说短信验证成功后
                if (result == SMSSDK.RESULT_COMPLETE) {
                    @SuppressWarnings("unchecked")
                    HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
                    String country = (String) phoneMap.get("country");
                    String phone = (String) phoneMap.get("phone");

                    // 提交用户信息（此方法可以不调用）
                    registerUser(country, phone);
                }
            }
        });
        registerPage.show(context);



    }

    //短信验证成功后会获取的信息
    private void registerUser(String country, String phone) {

        ToastMake.showToast(phone+"验证成功");
        StartActivity(MainActivity.class,true);

    }
}
